package org.ccay.excel.importer.service.impl.internal;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.ccay.core.io.VFSFileObject;
import org.ccay.core.log.CcayLoggerFactory;

//import org.apache.log4j.lf5.util.StreamUtils;

import org.ccay.core.log.ILogger;
import org.ccay.core.util.StreamUtil;
import org.ccay.excel.importer.ExcelCellError;
import org.ccay.excel.importer.ICellErrorAppender;

/**
 * 错误信息记录文件。
 * 
 * @author chaowangbang
 * @since Mar 27, 2012
 */
public class FileAppender implements ICellErrorAppender {

	/**
	 * 行分隔符
	 */
	public final static String LINE_SEP = "\r\n";

	/**
	 * 日志记录器
	 */
	private ILogger logger = CcayLoggerFactory.getLogger(FileAppender.class);
	
	private VFSFileObject fileObject;

	protected String encoding;

	private Writer writer;
	/**
	 * @param fileName
	 * @throws IOException
	 */
	public FileAppender(VFSFileObject fileObject) throws IOException {
		this.fileObject = fileObject;
		this.writer =  createWriter(fileObject.getOutputStream());
	}


	/* (non-Javadoc)
	 * @see org.ccay.excel.importer.ICellErrorAppender#append(org.ccay.excel.importer.ExcelCellError)
	 */
	public void append(ExcelCellError error) {
		try {
			this.writer.append(error.toString());
			this.writer.append(LINE_SEP);
		} catch (IOException ioe) {
			logger.error("Append excel cell error failed.", ioe);
		}
	}

	/* (non-Javadoc)
	 * @see org.ccay.excel.importer.ICellErrorAppender#close()
	 */
	public void close() {
		if(this.writer != null) {
			try {
				this.writer.flush();				
			} catch (IOException ioe) {
				logger.error("Could not close " + this.writer, ioe);
			}
		}
		StreamUtil.closeStreams(writer);
		fileObject.close();
	}

	/**
	 * 获取编码信息。
	 * 
	 * @return
	 */
	public String getEncoding() {
		return encoding;
	}

	/**
	 * 设置编码
	 * 
	 * @param value
	 */
	public void setEncoding(String value) {
		encoding = value;
	}

	/**
	 * 创建一个Writer.
	 * 
	 * @param os
	 * @return
	 */
	protected OutputStreamWriter createWriter(OutputStream os) {
		OutputStreamWriter retval = null;

		String enc = getEncoding();
		if(enc != null) {
			try {
				retval = new OutputStreamWriter(os, enc);
			} catch(IOException e) {
				logger.warn("Error initializing output writer.");
				logger.warn("Unsupported encoding?");
			}
		}

		if(retval == null) {
			retval = new OutputStreamWriter(os);
		}

		return retval;
	}

}
